import $env from '@/env.js'
import $store from '@/store/index.js';

import config from '@/admin.config.js'

/** 拦截器 */
const interceptor = {
  before(args) {
    if (!args.header) {
      args.header = {}
    }

    if (!args.method) {
      args.method = "POST";
    }

    if (args.url.indexOf("/") == 0) {
      args.url = args.url.substr(1, args.url.length)
    }

    let token = uni.getStorageSync('user_token') || '';
    if (token && token != 'undefined') {
      args.header['Authorization'] = "bearer " + token;
    }


    if ($env.API_MOCK) {
      args.url = "/static/mock/" + args.url + '.json'
    } else {
      args.url = $env.PROJECT_API_BASE_URL /*  */ + args.url
    }
  },
  after(response, request) {
    console.log('请求地址：', request.url, '\n请求信息：', request.data, '\n相应内容：', response)
  },
  returnValue(response, resolve, reject) {
    if (response.statusCode != 200) {
      uni.showToast({
        mask: true,
        icon: "none",
        duration: 3000,
        title: '服务器异常(' + response.statusCode + ')，请稍后重试',
      })
      // uni.redirectTo({
      //   url: config.login.url
      // })
      reject();
      return;
    }

    const {
      code,
      msg,
      data
    } = response.data;

    //统一输入输出请求信息
    switch (parseInt(code)) {
      case 500:
        uni.showModal({
          title: "提示",
          content: msg,
          showCancel: false
        });
        reject();
        break;
      case 200:
        resolve(data)
        break;
      case 400:
        uni.showModal({
          title: msg,
          mask:true,
          showCancel:false
        });
        reject()
        break;
      case 403:
        $store.commit('user/REMOVE_TOKEN');
        uni.redirectTo({
          url: config.login.url
        })
        reject(msg);
        break;
      default:
        uni.showModal({
          title: "服务异常，请稍后重试.",
          mask:true,
          showCancel:false,
          success() {
            // uni.redirectTo({
            //   url: config.login.url
            // })
          }
        });
    }
  }
}

uni.addInterceptor('uploadFile', {
  invoke: (args) => {
    interceptor.before(args)
  },
  success(response, request) {
    interceptor.after(response, request)
  },
  returnValue(res) {
    return new Promise((resolve, reject) => {
      res.then(response => {
        response.data = JSON.parse(response.data)
        interceptor.returnValue(response, resolve, reject);
      });
    });
  }
})

//API拦截器
uni.addInterceptor('request', {
  invoke: (args) => {
    interceptor.before(args)
  },
  success(response, request) {
    interceptor.after(response, request)
  },
  returnValue(res) {
    return new Promise((resolve, reject) => {
      res.then(response => {
        interceptor.returnValue(response, resolve, reject);
      });
    });
  }
});